/*jslint vars: true, forin: true, sloppy: true */
/*global DialogInstance, ocDialog, angular */
ocDialog.directive('ocFile', function ($filter) {
	var dateFilter = $filter('date');

	return {
		restrict: 'E',
		transclude: true,
		replace: true,
		template:
			'<div class="oc-file" oc-draggable>' +
				'<header oc-draggable-handle><label>{{action}} - {{title}}</label></header>' +
				'<nav><button class="danger close" oc-dialog-close></button></nav>' +
				'<section><nav class="oc-toolbar" style="border-bottom:1px solid #ccc"><input /></nav>' +
					'<oc-data-list setup="file"></oc-data-list>' +
					'<input ng-model="fileName" />' +
					'<button class="text-but cancel" oc-dialog-close ' +
						'ng-click="closeWith($event)">{{action}}</button>' +
				'</section></div>',
		scope: {},
		compile: function () {
			return {
				pre: function (scope, element, attr) {
					var data = [];
					scope.keyName = scope.name || 'name';
					scope.keyUpdateTime = scope.updateTime || 'updateTime';
					scope.dataList = scope.dataList || [{name: '未配置列表数据', updateTime: Date.now()}];

					angular.forEach(scope.dataList, function (row, index) {
						this.push({
							name: row[scope.keyName],
							updateTime: dateFilter(row[scope.keyUpdateTime], 'yyyy-MM-dd')
						});
					}, data);

					scope.file = {
						field: [
							{
								key: 'name',
								title: '名称',
								width: '19rem'
							},
							{
								key: 'updateTime',
								title: '修改日期',
								width: '4rem'
							}
						],
						data: data,
						selectFn: function (index) {
							scope.fileName = this[index][scope.keyName];
						}
					};

					// Set the action button behiever when it was clicked.
					scope.closeWith = function (event) {
						(scope.actionFn || angular.noop)(scope.file.selected, scope.fileName, event);
					};

					// The DI of this oc-file dialog.
					return new DialogInstance(element, scope);
				}
			};
		}
	};
});
